package com.coders.audio;

import java.io.IOException;

import android.media.MediaPlayer;
import android.media.MediaRecorder;

import com.coders.util.Logger;

/**
 * {@link AudioManager} implementation based on {@link MediaRecorder}.
 * 
 * @author subin
 * 
 */
public class AudioManagerImpl implements AudioManager
{
    private MediaRecorder recorder = new MediaRecorder();
    private MediaPlayer   mediaPlayer;

    public void start( String path ) throws IOException
    {
        String state = android.os.Environment.getExternalStorageState();

        if ( !state.equals( android.os.Environment.MEDIA_MOUNTED ) )
        {
            Logger.error( "SD Card is not mounted.  It is " + state );
        }

        recorder = new MediaRecorder();
        recorder.setAudioSource( MediaRecorder.AudioSource.MIC );
        recorder.setOutputFormat( MediaRecorder.OutputFormat.THREE_GPP );
        recorder.setAudioEncoder( MediaRecorder.AudioEncoder.AMR_NB );
        recorder.setOutputFile( path );
        recorder.prepare();
        recorder.start();
    }

    public void stop() throws IOException
    {
        if ( null != recorder )
        {
            recorder.stop();
            recorder.reset();
            recorder.release();
            recorder = null;
        }
    }

    public void play( String path ) throws IOException
    {
        // This will create a NEW MediaPlayer every time. But its fine for the
        // time being.
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource( path );
        mediaPlayer.prepare();
        mediaPlayer.start();
    }
    public void Pause()
    {        
    
          if (recorder != null) 
   {          
        	  recorder.release();
        	  recorder = null;   
        }       
    if ( mediaPlayer != null) {  

    	 mediaPlayer.release();      
    	 mediaPlayer = null;       
    }  
     }
}